package com.feiyi.app.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.feiyi.app.MainActivity;
import com.feiyi.app.R;
import com.feiyi.app.adapter.DetailPagerAdapter;
import com.feiyi.app.adapter.DetailRecommendGoodsAdapter;
import com.feiyi.app.adapter.goodsdetail.GoodsCommentAdapter;
import com.feiyi.app.app.AppConstant;
import com.feiyi.app.base.BaseActivity;
import com.feiyi.app.bean.GoodsAddToCartBean;
import com.feiyi.app.bean.GoodsDetailBean;
import com.feiyi.app.fragment.goodsdetail.GoodsInfoWebFragment;
import com.feiyi.app.net.HttpMethods;
import com.feiyi.app.utils.FitStateUI;
import com.feiyi.app.utils.ImageUtil;
import com.feiyi.app.view.SpaceItemDecoration;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * 作者 : wlt
 * 创建时间:  2018-07-30
 * QQ : 1346947404
 * 邮箱:wanglt_android@163.com
 * 类说明:
 * In me the tiger sniffs the rose
 */

public class GoodsDetailActivityNew extends BaseActivity {

    Unbinder unbinder;

    @BindView(R.id.back)//返回按钮
    ImageView back;
    @BindView(R.id.vp_viewpager)//展示图片的viewpager
    ViewPager vp_viewpager;
    @BindView(R.id.tv_page_number)//图片顺序
    TextView tvNumber;
    @BindView(R.id.tv_goods_name)//商品名称
    TextView tvGoodsName;
    @BindView(R.id.tv_goods_price)//商品价格
    TextView tvGoodsPrice;
    @BindView(R.id.tv_goods_weight)//商品重量
    TextView tvGoodsWeight;
    @BindView(R.id.tv_discounts)//商品优惠信息
    TextView tvDiscounts;
    @BindView(R.id.ll_comment)//评价的总布局
    LinearLayout ll_comment;
    @BindView(R.id.rv_comment)//评价的列表
    RecyclerView rv_comment;
    @BindView(R.id.tv_no_comment)//无商品评价的提示
    TextView tv_no_comment;
    @BindView(R.id.tv_show_more_comment)//加载更多评价
    TextView tv_show_more_comment;
    @BindView(R.id.wv_goods_detail)//商品详情的webview
    WebView wv_goods_detail;
    @BindView(R.id.ll_relate_goods)//相关商品布局
    LinearLayout ll_relate_goods;
    @BindView(R.id.rv_detail_recommend)//相关商品列表
    RecyclerView rv_detail_recommend;
    @BindView(R.id.iv_goods_focus)//商品关注的标识
    ImageView iv_goods_focus;
    @BindView(R.id.tv_goods_detail_focus)//商品关注
    TextView tv_goods_detail_focus;
    /**
     * 商品评价列表适配器
     */
    private GoodsCommentAdapter goodsCommentAdapter;
    /**
     * 商品评价列表数据
     */
    private List<GoodsDetailBean.DataBean.CommentsBean> commentsBeanList = new ArrayList<>();
    /**
     * 网络获取数据存本地
     */
    private GoodsDetailBean detailBean;
    /**
     * 推荐商品数据列表
     */
    private List<GoodsDetailBean.DataBean.RecommendGoodsBean> recommendGoodsBeanList = new ArrayList<>();
    /**
     * 商品推荐列表适配器
     */
    private DetailRecommendGoodsAdapter recommendGoodsAdapter;
    /**
     * 顶部轮播图的数据
     */
    private List<String> imgList = new ArrayList<>();
    /**
     * 顶部轮播图的适配器
     */
    private DetailPagerAdapter detailPagerAdapter;
    /**
     * 商品ID
     */
    private String goods_id;
    /**
     * 用户id
     */
    private String uid;
    /**
     * 用户session id
     */
    private String sid;

    private static final String TAG = "main";
    /**
     * webview的设置
     */
    private WebSettings webSettings;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        FitStateUI.setImmersionStateMode(this);
        setContentView(R.layout.activity_goods_detail_new);
        unbinder = ButterKnife.bind(this);
        getGoodsId();
        initAdapter();
        initData();
    }

    private void getGoodsId() {
        goods_id = getIntent().getStringExtra("goods_id");

        uid = spUtils.getString(AppConstant.UID);
        sid = spUtils.getString(AppConstant.SID);
    }

    private void initAdapter() {
        /**
         * LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
         mLayoutManager.setSmoothScrollbarEnabled(true);
         mLayoutManager.setAutoMeasureEnabled(true);
         mRecyclerView.setLayoutManager(mLayoutManager);
         mRecyclerView.setHasFixedSize(true);
         mRecyclerView.setNestedScrollingEnabled(false);
         */

        goodsCommentAdapter = new GoodsCommentAdapter(R.layout.item_goods_recommend,commentsBeanList);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setSmoothScrollbarEnabled(true);
        mLayoutManager.setAutoMeasureEnabled(true);
        rv_comment.setLayoutManager(mLayoutManager);
        rv_comment.setHasFixedSize(true);
        rv_comment.setNestedScrollingEnabled(false);
        rv_comment.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        rv_comment.setAdapter(goodsCommentAdapter);

        recommendGoodsAdapter = new DetailRecommendGoodsAdapter(R.layout.item_home_goods,recommendGoodsBeanList);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,3);
        gridLayoutManager.setSmoothScrollbarEnabled(true);
        gridLayoutManager.setAutoMeasureEnabled(true);
        rv_detail_recommend.setLayoutManager(gridLayoutManager);
        rv_detail_recommend.setHasFixedSize(true);
        rv_detail_recommend.setNestedScrollingEnabled(false);
        rv_detail_recommend.addItemDecoration(new SpaceItemDecoration(20));
        rv_detail_recommend.setAdapter(recommendGoodsAdapter);

        detailPagerAdapter = new DetailPagerAdapter(this,imgList);
        vp_viewpager.setAdapter(detailPagerAdapter);
        vp_viewpager.setOnPageChangeListener(new MyOnPageChangeListener());

        rv_detail_recommend.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("goods_id",recommendGoodsBeanList.get(position).getGoods_id());
                ActivityUtils.startActivity(bundle,GoodsDetailActivityNew.class);
            }
        });
    }

    private void initData() {
        FormBody.Builder builder = new FormBody.Builder();
        if (null != sid){
            builder.add("sid",sid);
        }
        if (null != uid){
            builder.add("uid",uid);
        }

        builder.add("goods_id",goods_id);
        RequestBody body = builder.build();
        HttpMethods.getInstance().info.getGoodsDetail(AppConstant.GOODS_DETAIL,body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GoodsDetailBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(GoodsDetailBean goodsDetailBean) {
                        Log.e("main", "onNext: "+goodsDetailBean.toString() );
                        if (goodsDetailBean.getStatus().getSucceed() == 1){
                            detailBean = goodsDetailBean;
                            init();
                        }else {
                            ToastUtils.showShort(goodsDetailBean.getStatus().getError_desc());
                            ActivityUtils.startActivity(LoginActivity.class);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: "+e.toString() );
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    private void init(){
        imgList.add(detailBean.getData().getImg().getThumb());
        imgList.add(detailBean.getData().getImg().getThumb());
        imgList.add(detailBean.getData().getImg().getThumb());
        ImageUtil.suitDisplay(vp_viewpager,1,1,1,1);
        detailPagerAdapter.notifyDataSetChanged();

        tvGoodsName.setText(detailBean.getData().getGoods_name());
        tvGoodsPrice.setText(detailBean.getData().getMarket_price());
        tvGoodsWeight.setText("重量 : "+detailBean.getData().getGoods_weight());
        if (detailBean.getData().getCollected() == 1){
            iv_goods_focus.setImageResource(R.mipmap.focus);
            tv_goods_detail_focus.setText("已关注");
        }else {
            iv_goods_focus.setImageResource(R.mipmap.focus);
            tv_goods_detail_focus.setText("加关注");
        }

        if (null != detailBean.getData().getComments() && !detailBean.getData().getComments().isEmpty()){
            StringBuilder builder = new StringBuilder();
            if (detailBean.getData().getComments().size() >= 2){
                builder.append(detailBean.getData().getDiscounts().get(0)).append("/").append(detailBean.getData().getDiscounts().get(1));
                tvDiscounts.setText(builder);
            }else {
                builder.append(detailBean.getData().getDiscounts().get(0));
                tvDiscounts.setText(builder);
            }
        }

        if (null != detailBean.getData().getComments() && !detailBean.getData().getComments().isEmpty()){
            tv_no_comment.setVisibility(View.GONE);
            tv_show_more_comment.setVisibility(View.VISIBLE);
            ll_comment.setVisibility(View.VISIBLE);
            commentsBeanList.addAll(detailBean.getData().getComments());
            goodsCommentAdapter.notifyDataSetChanged();
        }else {
            tv_no_comment.setVisibility(View.VISIBLE);
            tv_show_more_comment.setVisibility(View.GONE);
            ll_comment.setVisibility(View.GONE);
        }

        initWebView();

        wv_goods_detail.loadUrl(AppConstant.GOODSDETAIL_DESC+goods_id);
        if (null != detailBean.getData().getRecommend_goods() && !detailBean.getData().getRecommend_goods().isEmpty()){
            recommendGoodsBeanList.addAll(detailBean.getData().getRecommend_goods());
            recommendGoodsAdapter.notifyDataSetChanged();
        }
    }

    private void initWebView() {
        webSettings = wv_goods_detail.getSettings();
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setBlockNetworkImage(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        wv_goods_detail.setWebViewClient(new GoodsDetailWebViewClient());
    }
    @OnClick({R.id.rl_focus,R.id.rl_shopping_cart,R.id.rl_buy_now,R.id.back,R.id.share})
    public void onClick(View view){

        switch (view.getId()){

            case R.id.back:
                finish();
                break;
            case R.id.share:
                break;
            case R.id.rl_focus:
//                ToastUtils.showShort("暂无");
                break;
            case R.id.rl_shopping_cart:
                finish();
                Intent intent = new Intent(this,MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                intent.putExtra("shop_cart","y");
                startActivity(intent);
                break;
            case R.id.rl_buy_now:
                addToCart();
                break;







        }



    }

    private void addToCart(){
        uid = spUtils.getString(AppConstant.UID);
        sid = spUtils.getString(AppConstant.SID);
        if (null != sid && null != uid){
            Log.e(TAG, "addToCart: "+uid+"__"+sid );
        }
        if (null == sid || null == uid){
            ToastUtils.showShort("请先登录");
            ActivityUtils.startActivity(LoginActivity.class);
        }else {
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("sid",sid);
            builder.add("uid",uid);
            builder.add("goods_id",goods_id);
            builder.add("number","1");
            RequestBody body = builder.build();
            HttpMethods.getInstance().info.addToCart(AppConstant.ADD_TO_CART_URL,body)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<GoodsAddToCartBean>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(GoodsAddToCartBean goodsAddToCartBean) {
                            if (goodsAddToCartBean.getStatus().getSucceed() == 1){
                                ToastUtils.showShort("加入购物车成功");
                                EventBus.getDefault().post("change");
                            }else {
                                ToastUtils.showShort("加入购物车失败,"+goodsAddToCartBean.getStatus().getError_desc());
                                ActivityUtils.startActivity(LoginActivity.class);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    private class GoodsDetailWebViewClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            webSettings.setBlockNetworkImage(false);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true;
        }
    }
    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(int position) {
            tvNumber.setText(new StringBuilder().append((position) % imgList.size() + 1).append("/")
                    .append(imgList.size()));
//            titleTv.setText(list.get(position % list.size()).getAd_name());
            // 获取真实的索引
//    		int realPosition = position % list.size();
//            numberTv.setText(new StringBuilder().append((position) % list.size() + 1).append("/")
//                    .append(list.size()));
            //TODO 改变小点的选中状态
//            for (int i = 0; i <list.size(); i++) {
//                if (i == position%list.size()) {
//                    ll_point.getChildAt(i).setEnabled(true);
//                }else{
//                    ll_point.getChildAt(i).setEnabled(false);
//                }
//            }

        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        dispose();

    }
}
